package com.blog.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.entity.Article;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface ArticleMapper extends BaseMapper<Article> {

    @Select("SELECT a.*, c.name as categoryName, u.nickname FROM article a LEFT JOIN category c ON a.category_id = c.id LEFT JOIN user u ON a.user_id = u.id WHERE (#{status} IS NULL OR #{status} = -1 OR a.status = #{status}) AND (#{userId} IS NULL OR a.user_id = #{userId}) AND (#{categoryId} IS NULL OR a.category_id = #{categoryId}) ORDER BY a.create_time DESC")
    IPage<Article> findArticlesWithCategoryName(IPage<Article> page, @Param("status") Integer status, @Param("userId") Long userId, @Param("categoryId") Long categoryId);

    @Select("SELECT COUNT(*) FROM article a LEFT JOIN category c ON a.category_id = c.id WHERE (#{status} IS NULL OR #{status} = -1 OR a.status = #{status}) AND (#{userId} IS NULL OR a.user_id = #{userId}) AND (#{categoryId} IS NULL OR a.category_id = #{categoryId})")
    Long countArticlesWithCategoryName(@Param("status") Integer status, @Param("userId") Long userId, @Param("categoryId") Long categoryId);

    @Select("SELECT a.*, c.name as categoryName, u.nickname FROM article a LEFT JOIN category c ON a.category_id = c.id LEFT JOIN user u ON a.user_id = u.id WHERE a.id = #{id}")
    Article findArticleWithDetails(@Param("id") Long id);

    @Select("SELECT a.*, c.name as categoryName, u.nickname FROM article a LEFT JOIN category c ON a.category_id = c.id LEFT JOIN user u ON a.user_id = u.id WHERE a.category_id = #{categoryId} AND a.status = 1 ORDER BY a.create_time DESC")
    IPage<Article> findByCategoryWithDetails(IPage<Article> page, @Param("categoryId") Long categoryId);

    @Select("SELECT a.*, c.name as categoryName, u.nickname FROM article a LEFT JOIN category c ON a.category_id = c.id LEFT JOIN user u ON a.user_id = u.id WHERE a.user_id = #{userId} ORDER BY a.create_time DESC")
    IPage<Article> findByUserWithDetails(IPage<Article> page, @Param("userId") Long userId);
    
    @Select("SELECT c.id as categoryId, c.name as categoryName, COUNT(a.id) as articleCount " +
           "FROM category c " +
           "LEFT JOIN article a ON c.id = a.category_id AND a.status = 1 " +
           "GROUP BY c.id, c.name " +
           "ORDER BY articleCount DESC")
    List<Map<String, Object>> getCategoryArticleStats();
} 